import BaseComponent from "../../app/baseComponent";
import { addYears, subYears } from 'date-fns'

export class AuiYear extends BaseComponent {
    constructor(name) {
        super(name);
        this.props = {
            onRenderDates: {
                required: true
            },            
            now: {
                type: Date,
                default: new Date()
            }
        };
        this.computed = {
            range() {
                return `${this.private_startYear} - ${this.private_endYear}`;
            }
        };
        this.methods = {
            render(date) {
                var self = this;

                if (date) {
                    self.now = date;
                }

                self.private_currentYear = self.now.getFullYear();
                self.private_startYear = self.private_currentYear;
                self.private_endYear = self.private_currentYear + 20;

                var dates = [];
            
                for (var i = self.private_startYear; i < self.private_endYear; i++) {
                    dates.push({
                        className: `${name}__year`,
                        text: i,
                        year: i,
                        origin: {}                       
                    });
                }

                if (self.onRenderDates) {
                    dates = self.onRenderDates(dates);
                }

                self.private_dates = dates;
            },
            prev() {
                var self = this;
                self.now = subYears(self.now, 20);
                self.render();
            },
            next() {
                var self = this;
                self.now = addYears(self.now, 20);
                self.render();
            },
            private_handleYearClick(e) {
                this.$emit("yearselect", e);
            }            
        };      
    }
    _template() {
        var self = this;
return `
<div class="${self._name}">
    <div class="${self._name}__actions"><button class="${self._name}__action" type="button" @click="prev"><span class="${self._name}__iconprev"></span></button><div class="${self._name}__action ${self._name}__range">{{range}}</div><button class="${self._name}__action" type="button" @click="next"><span class="${self._name}__iconnext"></span></button></div>    
    <div class="${self._name}__years"><div :class="date.className" 
    :data-year="date.year" @click="private_handleYearClick" v-for="date in private_dates">{{date.text}}</div></div>
</div>
`        
    }
    _mounted() {                
        var self = this;    
        self.render();    
    }    
    _data() {
        var ret = {};
        
        ret.private_currentYear = 0;
        ret.private_startYear = 0;
        ret.private_endYear = 0;

        ret.private_dates = [];

        return ret;        
    }      
}

AuiYear.install = function() {
    window.AUICustomComponents.define("aui-year", AuiYear);
}